package org.groovyflow.db

import groovy.sql.*
import javax.sql.*

/**
 * @author Chuck Tassoni
 */

class Transaction {
   def dataSource
   Transaction(dataSource){
     this.dataSource = dataSource
   }
   def exe(closu){
   	  def conn = ConnectionThreadLocal.getConnection()
	  //Join an existing transation, if one's there
   	  if(conn != null){
   	     println "Running a closure inside an existing transaction using conn = " + conn
   	  	 def sql = new Sql(conn)
   	  	 println 'sql has been created: ' + sql
   	  	 def ret = closu(sql)
   	  	 println "Finished runnning a closure inside an existing transaction using conn = " + conn
   	  	 return ret
   	  }
   	  else
   	  	return startNewTrx(closu)
   	 
   }
   
   def startNewTrx(closu){
      def conn = dataSource.getConnection()
      println "Starting a new transaction with conn = " + conn
      conn.setAutoCommit(false)
      ConnectionThreadLocal.setConnection conn
      def sql = new Sql(conn)
      try{
         def ret = closu(sql)
         conn.commit()
         return ret
      }catch(Exception ex){
         conn.rollback()
         ex.printStackTrace()
         throw ex
      }finally{
          println "new transaction is finished.  Used conn = " + conn
          conn.close()
          ConnectionThreadLocal.setConnection null 
      }    
   
   }

}